#include "mystdio.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>

MyFile* MyFopen(const char *path,const char *mode)
{
    int fd = -1;
    if(strcmp("r",mode)==0)
    {
        fd = open(path,O_RDONLY);
    }
    else if(strcmp("w",mode)==0)
    {
        fd = open(path,O_CREAT | O_TRUNC | O_WRONLY,0666);
    }
    else if(strcmp("a",mode)==0)
    {
        fd = open(path,O_CREAT | O_APPEND | O_WRONLY,0666);
    }
    if(fd<0) return NULL;
    MyFile *pf = (MyFile*)malloc(sizeof(MyFile));
    pf->fileno = fd;
    pf->bufflen = 0;
    pf->mode = LINE_FLUSH;
    memset(pf->buff,0,MAX_SIZE);
    return pf;
}

void MyFclose(MyFile *pf)
{
    MyFflush(pf);
    free((void*)pf);
    close(pf->fileno);
}

void MyFflush(MyFile *pf)
{
    if(pf->bufflen>0)
    {
        write(pf->fileno,pf->buff,pf->bufflen);
        fsync(pf->fileno);
        pf->bufflen = 0;
    }
}

size_t MyFwrite(const void *ptr, size_t size, size_t numb, MyFile *pf)
{
    size_t total = size*numb;
    //写不下，先刷新
    if(total+pf->bufflen>=MAX_SIZE)
    {
        MyFflush(pf);
    }
    strncpy(pf->buff+pf->bufflen,(const char*)ptr,total);
    pf->bufflen += total;
    if((pf->mode & LINE_FLUSH) && pf->buff[pf->bufflen-1]=='\n')
    {
        MyFflush(pf);
    }
    return total;
}
